package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.MemberDao;
import com.itheima.dao.RecordDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.pojo.Record;
import com.itheima.service.MemberService;
import com.itheima.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

@Service(interfaceClass = MemberService.class)
@Transactional
public class MemberServiceImpl implements MemberService {

    @Autowired
    private MemberDao memberDao;
    @Autowired
    private RecordDao recordDao;

    @Override
    public Member findByTelephone(String telephone) {
        return memberDao.findByTelephone(telephone);
    }

    @Override
    public void add(Member member) {
        memberDao.addLogin(member);
    }

    @Override
    public Map getMemberReport() {
        Map<String,Object> map = new HashMap<>();

        //算出当前日期和一年前的日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        Calendar c = Calendar.getInstance();
        String end = sdf.format(c.getTime())+"-31";
        c.add(Calendar.MONTH,-11);
        String start = sdf.format(c.getTime())+"-1";

        List<Map> list = memberDao.getMemberReport(start,end);

        List<String> memberDates = new ArrayList<>();
        List<Long> memberCounts = new ArrayList<>();

        if ( list != null && list.size() > 0 ) {
            for (Map report : list) {
                String months = (String) report.get("months");
                Long memberCount = (Long) report.get("memberCount");
                memberDates.add(months);
                memberCounts.add(memberCount);
            }
            map.put("months",memberDates);
            map.put("memberCount",memberCounts);
        }
        return map;
    }

	
	 /**
     * 根据月份获取新增会员
     * @param list
     * @return
     */
    @Override
    public List<Integer> getMemberCountByMonth(List<String> list) {
        List<Integer> memberCount = new ArrayList<>();
        for (String month : list) {
            month = month + ".31";
            Integer count = memberDao.getMemberCountByMonth(month);
            memberCount.add(count);
        }
        return memberCount;
    }
	
	  /**
     * 后台查询会员档案
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        Page<Map> page = memberDao.findPage(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(),page.getResult());
    }
	
	 /**
     * 后台添加会员和关联档案
     * @param map
     */
    @Override
    public void backendAdd(Map map) {
        Member member = new Member();
        member.setFileNumber((String) map.get("fileNumber"));
        member.setName((String) map.get("name"));
        member.setSex((String) map.get("sex"));
        member.setIdCard((String) map.get("idCard"));
        member.setPhoneNumber((String) map.get("phoneNumber"));
        member.setRemark((String) map.get("remark"));
        member.setRegTime(DateUtils.getToday());
        memberDao.add(member);

        Integer memberId = member.getId();
        Record record = new Record();
        record.setFileStatus("已启用");  // 添加时默认启用档案
        record.setMemberId(memberId);
        record.setHealthManager((String) map.get("healthManager")); // 健康管理师
        record.setFileNumber((String) map.get("fileNumber")); // 档案号
        record.setAge((String) map.get("age")); // 年龄
        record.setHeight((String) map.get("height")); // 身高
        record.setWeight((String) map.get("weight")); // 体重
        record.setRemark((String) map.get("remark"));// 注意事项
        record.setDiastolicPressure((String) map.get("diastolicPressure")); // 舒张压
        record.setSystolicPressure((String) map.get("systolicPressure")); // 收缩压
        record.setRespiratoryFrequency((String) map.get("respiratoryFrequency")); // 呼吸频次
        record.setTemperature((String) map.get("temperature")); // 体温
        record.setWaistline((String) map.get("waistline")); // 腰围
        record.setHipline((String) map.get("hipline")); // 臀围
        record.setBmi((String) map.get("bmi")); // BMI
        record.setBloodOxygenConcentration((String) map.get("bloodOxygenConcentration")); // 血氧浓度
        record.setPastHistory((String) map.get("pastHistory")); // 既往史
        record.setFamilyHistory((String) map.get("familyHistory")); // 家族史
        record.setAllergicHistory((String) map.get("allergicHistory")); // 过敏史
        record.setMedicalHistory((String) map.get("medicalHistory")); // 病史
        record.setChronicDisease((String) map.get("chronicDisease")); // 慢性病
        recordDao.add(record);
    }

    /**
     * 根据会员id查询会员及其档案
     * @param id
     * @return
     */
    @Override
    public Result findMemberAndRecordById(Integer id) {
        Member member = memberDao.findById(id);
        Record record = recordDao.findByFileNumber(member.getFileNumber());
        Map<String,Object> map = new HashMap<>();
        map.put("id",id);
        map.put("fileNumber",member.getFileNumber());
        map.put("name",member.getName());
        map.put("idCard",member.getIdCard());
        map.put("sex",member.getSex());
        map.put("phoneNumber",member.getPhoneNumber());
        map.put("remark",member.getRemark());
        map.put("healthManager",record.getHealthManager());
        map.put("age",record.getAge());
        map.put("height",record.getHeight());
        map.put("weight", record.getWeight());
        map.put("diastolicPressure",record.getDiastolicPressure());
        map.put("systolicPressure",record.getSystolicPressure());
        map.put("respiratoryFrequency",record.getRespiratoryFrequency());
        map.put("temperature",record.getTemperature());
        map.put("waistline",record.getWaistline());
        map.put("hipline",record.getHipline());
        map.put("bmi",record.getBmi());
        map.put("bloodOxygenConcentration",record.getBloodOxygenConcentration());
        map.put("pastHistory",record.getPastHistory());
        map.put("familyHistory",record.getFamilyHistory());
        map.put("allergicHistory",record.getAllergicHistory());
        map.put("medicalHistory",record.getMedicalHistory());
        map.put("chronicDisease",record.getChronicDisease());
        return new Result(true, MessageConstant.EDIT_MEMBER_SUCCESS,map);
    }

    /**
     * 编辑会员和档案
     * @param map
     * @return
     */
    @Override
    public Result update(Map map) {
        Member member = new Member();
        member.setFileNumber((String) map.get("fileNumber"));
        member.setName((String) map.get("name"));
        member.setSex((String) map.get("sex"));
        member.setIdCard((String) map.get("idCard"));
        member.setPhoneNumber((String) map.get("phoneNumber"));
        member.setRemark((String) map.get("remark"));
        member.setRegTime(DateUtils.getToday());
        memberDao.updateByFileNumber(member); // 根据档案号更新会员信息


        Record record = new Record();
        record.setHealthManager((String) map.get("healthManager")); // 健康管理师
        record.setFileNumber((String) map.get("fileNumber")); // 档案号
        record.setAge((String) map.get("age")); // 年龄
        record.setHeight((String) map.get("height")); // 身高
        record.setWeight((String) map.get("weight")); // 体重
        record.setRemark((String) map.get("remark"));// 注意事项
        record.setDiastolicPressure((String) map.get("diastolicPressure")); // 舒张压
        record.setSystolicPressure((String) map.get("systolicPressure")); // 收缩压
        record.setRespiratoryFrequency((String) map.get("respiratoryFrequency")); // 呼吸频次
        record.setTemperature((String) map.get("temperature")); // 体温
        record.setWaistline((String) map.get("waistline")); // 腰围
        record.setHipline((String) map.get("hipline")); // 臀围
        record.setBmi((String) map.get("bmi")); // BMI
        record.setBloodOxygenConcentration((String) map.get("bloodOxygenConcentration")); // 血氧浓度
        record.setPastHistory((String) map.get("pastHistory")); // 既往史
        record.setFamilyHistory((String) map.get("familyHistory")); // 家族史
        record.setAllergicHistory((String) map.get("allergicHistory")); // 过敏史
        record.setMedicalHistory((String) map.get("medicalHistory")); // 病史
        record.setChronicDisease((String) map.get("chronicDisease")); // 慢性病
        recordDao.updateByFileName(record);
        return new Result(true,MessageConstant.EDIT_MEMBER_SUCCESS);
    }

    @Override
    public Result deleteFile(String fileNumber) {
        memberDao.deleteFileNumber(fileNumber);
        recordDao.deleteFileNumber(fileNumber);
        return new Result(true,MessageConstant.DELETE_MEMBER_SUCCESS);
    }
	
}
